package com.vinjogames.TankGame;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.vinjogames.entities.Game;
import com.vinjogames.gfx.AnimationManager;
import com.vinjogames.gfx.Camera;
import com.vinjogames.gfx.GameView;
import com.vinjogames.network.ConnectionManager;
import com.vinjogames.ui.TitleMenu;
import com.vinjogames.util.GameClock;
import com.vinjogames.util.GameConVars;
import com.vinjogames.util.InputManager;
import com.vinjogames.util.Logger;
import com.vinjogames.util.Preferences;
import com.vinjogames.util.SoundManager;

public class TankGameActivity extends Activity {
	Game mGame;
	TitleMenu mMenu;
	GameView mView;
	GameThread mThread;
	InputManager mInputManager;
	SoundManager mSoundManager;
	ConnectionManager mConnectionManager;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setUpDisplay();
		
		Logger.setContext(this);
		Preferences.setUpPrefs(this);
		
		mGame = new Game(this);
		mMenu = new TitleMenu();
		mView = new GameView(this);
		
		
		
		
		
		mThread = new GameThread(this);
		mConnectionManager = ConnectionManager.getInstance();
		mConnectionManager.init(this);
		mInputManager = InputManager.getInstance();
		mInputManager.init(this);
		mSoundManager = SoundManager.getInstance();
		
		setContentView(mView);
		mView.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent e) {
				mInputManager.handleTouchEvent(e); 
				return true;
			}
		});
		
		mMenu.init(this);
		mThread.start();
	}
	
	private void setUpDisplay(){
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);

		float width = 0;
		float height = 0;
		
		//This is to flip the screen //zachs bug if you start game with screen off
		if(metrics.widthPixels > metrics.heightPixels){
			width = metrics.widthPixels;
			height = metrics.heightPixels;
		}else{
			width = metrics.heightPixels;
			height = metrics.widthPixels;
		}
		
		float ratio = width/height;
		Camera.getInstance().setGLWIDTH(Camera.GL_HEIGHT*ratio);
		Camera.getInstance().setScreenSize((int)width,(int)height);
	}
	
	public Game getGame(){ return mGame; }

	public TitleMenu getMenu(){ return mMenu; }
	
	public GameView getView(){ return mView; }
	
	@Override
	protected void onPause(){
		super.onPause();//Pauses Activity Thread
		mView.onPause();//Pauses Renderer Thread
		mThread.pause();//Pauses GameThread

		mConnectionManager.close();//TODO:  
		Logger.log("[Activity]: onPause");
	}

	@Override
	protected void onResume(){
		super.onResume();
		mView.onResume();
		mThread.unpause();
		Logger.log("[Activity]: onResume");
	}
	
	@Override
	public void onBackPressed() {
		//saveGame(mGame.getSaveState());
        Logger.log("[Activity]: onBackPressed " + GameClock.getInstance().getTime());
		mThread.close();
        mConnectionManager.close();
        AnimationManager.getInstance().clearMemory();
        finish();
	}
	
	public boolean onKeyUp(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_MENU) {
	    	mInputManager.sendAction(GameConVars.INPUT_MENU, null, 0);
	    }
	    if(keyCode == KeyEvent.KEYCODE_BACK){
	    	mInputManager.sendAction(GameConVars.INPUT_QUIT, null, 0);
	    	onBackPressed();
	    }
	    return true;
	}
	
	public static Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) { 
			super.handleMessage(msg);
			String text = msg.getData().getString("Text");
			Logger.popUp(text);
		}
	};
	
	
	//TODO: Move to file manager
//	private void saveGame(Bundle save){
//		if(save == null)
//			return;
//		try {
//			FileOutputStream fos = openFileOutput("filename", Context.MODE_PRIVATE);
//			Parcel p = Parcel.obtain();
//			save.writeToParcel(p, 0);
//			fos.write(p.marshall());
//			fos.flush();
//			fos.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
//
//	private void loadGame(){
//		Bundle save = new Bundle();
//		byte[] buffer = new byte[0];//TODO:  MAX SAVE STATE SIZE
//		FileInputStream fis;
//		try {
//			fis = openFileInput("filename");
//			fis.read(buffer);
//			fis.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		Parcel p = Parcel.obtain();
//		p.unmarshall(buffer, 0, buffer.length);
//		p.setDataPosition(0);
//		save.readFromParcel(p);	
//		//bbv.loadGame(save, g);
//	}
}